/* eslint-disable import/order */
import { useSettings } from "@/store/settingStore";
import { useThemeToken } from "@/theme/hooks";
import { commonService } from "@/api/services/commonService";
import { message } from "antd";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { useState, useEffect } from "react";
import { StyledEditor } from "./styles";

interface Props {
	value?: string;
	onChange?: (html: string) => void;
	height?: number;
}

export default function RichTextEditor({
	value = "",
	onChange,
	height = 250,
}: Props) {
	const token = useThemeToken();
	const { themeMode } = useSettings();
	const [editor, setEditor] = useState<IDomEditor | null>(null);
	const [html, setHtml] = useState(value);

	useEffect(() => {
		setHtml(value);
	}, [value]);

	const toolbarConfig: Partial<IToolbarConfig> = {
		excludeKeys: [],
	};

	const editorConfig: Partial<IEditorConfig> = {
		placeholder: "请输入内容...",
		MENU_CONF: {
			uploadImage: {
				async customUpload(file: File, insertFn: any) {
					try {
						const formData = new FormData();
						formData.append("file", file);
						const response = await commonService.uploadFile(file);
						insertFn(response.url);
					} catch (error) {
						message.error("图片上传失败");
					}
				},
			},
		},
	};

	useEffect(() => {
		return () => {
			if (editor == null) return;
			editor.destroy();
			setEditor(null);
		};
	}, [editor]);

	return (
		<StyledEditor $token={token} $thememode={themeMode}>
			<div style={{ border: "1px solid #ccc", zIndex: 100 }}>
				<Toolbar
					editor={editor}
					defaultConfig={toolbarConfig}
					mode={themeMode === "dark" ? "dark" : "default"}
					style={{ borderBottom: "1px solid #ccc" }}
				/>
				<Editor
					defaultConfig={editorConfig}
					value={html}
					onCreated={setEditor}
					onChange={(editor) => {
						const content = editor.getHtml();
						const isEmpty = content === '<p><br></p>' || content === '';
						const finalContent = isEmpty ? '' : content;
						setHtml(finalContent);
						onChange?.(finalContent);
					}}
					mode={themeMode === "dark" ? "dark" : "default"}
					style={{ height: `${height}px`, overflowY: "hidden" }}
				/>
			</div>
		</StyledEditor>
	);
}
